import React, { Component } from 'react';
import { Tabs, Button,Table ,Divider,Modal ,Form,Input,Icon,Popover,InputNumber ,Select,Cascader, Drawer,Row,Col ,Popconfirm } from 'antd';
import '@/assets/css/settings';
import * as APIService from '../../axios/api';
import * as utils from '../../utils_yyr/action';
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;



const EditableContext = React.createContext();

class EditableCell extends React.Component {
	getInput = () => {
	  if (this.props.inputType === 'number') {
		return <InputNumber />;
	  }
	  return <Input />;
	};
  
	renderCell = ({ getFieldDecorator }) => {
	  const {
		editing,
		dataIndex,
		title,
		inputType,
		record,
		index,
		children,
		...restProps
	  } = this.props;
	  return (
		<td {...restProps}>
		  {editing ? (
			<Form.Item style={{ margin: 0 }}>
			  {getFieldDecorator(dataIndex, {
				rules: [
				  {
					required: true,
					message: `Please Input ${title}!`,
				  },
				],
				initialValue: record[dataIndex],
			  })(this.getInput())}
			</Form.Item>
		  ) : (
			children
		  )}
		</td>
	  );
	};
  
	render() {
	  return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
	}
  }
 class Settings extends Component {
	state = { loading: false, dataSource: [], visible: false,btnIcon:'' ,
	modalData:'',menuList:[],firstLevel:'',secondLevel:'',
	options:[],handleType:0,topId:0,btnDrawer:false,
	editingKey:'',btnData:[], key:1,
 };
	componentDidMount() {
		this.fetch(this.state.key);
	}
	//初始化加载数据
	fetch=(type)=>{
		const that=this;
		this.setState({loading:true})
		APIService.getMenus(type).then(data=>{
			const dataSource=data.data.data;
					const options=[];
					for(var value of dataSource){
					  var json = {"label":value.name,"value":value.id,'children':[]}
					 
					  if(value.children.length!==0){
                        for(var valueFirst of value.children){
							json.children.push({'label':valueFirst.name,'value':valueFirst.id})
						}
					  }
					  options.push(json);
					}
		            this.setState({
						menuList:dataSource,
						loading:false,
						options:options
					})
				
				 })
	}
	handleChangeTab = key => {
		if (parseInt(key) === 1) {
			this.fetch(1);
			this.setState({key:1})
		} else if (parseInt(key) === 2) {
			this.fetch(2)
			this.setState({key:2})
		}else if(parseInt(key) === 3){
			this.fetch(3)
			this.setState({key:3})
		}
	};
	//根据菜单id查询按钮
	getBtnByMenuId=(id)=>{
		const that=this;
		APIService.getBtnByMenuId(id).then(data=>{
			if(data.data.code===200){
				that.setState({
					btnData:data.data.data
				})
			}else{
				utils.openNotification('warning', data.data.msg)
			}		
		 })
	}
	//添加修改菜单提交
    submitMenu=(e)=>{
		this.props.form.validateFields(['menuName','address','sort','secondNode','firstNode'],(err, values) => {
			if (!err) {
				values.sort=parseInt(values.sort);
				var json={menuName:values.menuName,icon:this.state.btnIcon===''?'home':this.state.btnIcon,sort:values.sort,address:values.address};
				var parentId
				if(this.state.firstLevel==='block'){
					parentId=parseInt(values.firstNode);
				}else if(this.state.secondLevel==='block'){
					parentId=parseInt(values.secondNode[1]);
				}
				if(this.state.handleType===0){
					json=Object.assign({}, json,{creatorId:parseInt(localStorage.getItem('userId')),parentId:this.state.modalData.id===undefined?null:this.state.modalData.id,type:0 } )
				}else{
					json=Object.assign({}, json,{updaterId:parseInt(localStorage.getItem('userId')),parentId:parentId,type:0,id:this.state.modalData.id})
				}
								const that=this;
								json.type = this.state.key
				APIService.addMenu(json).then(data=>{
					if(data.data.code===200){
						utils.openNotification('success', '操作成功')
						APIService.queryUserById(localStorage.getItem('userId')).then(res=>{
							localStorage.setItem('menuList',JSON.stringify(res.data.data.menuTreeNodeList));
						})
					}else{
						utils.openNotification('warning', data.data.msg)
					}
					
					that.handleCancel();
					that.props.form.resetFields();
				  	that.fetch(that.state.key);
				 })
				 

				
			} else {
				console.log(err);
			}
		});
	}

    //新增按钮
    submitBtn=(form,key)=>{
		const that=this;
		var json;
		if(form===undefined){
			this.props.form.validateFields(['btnCode','btnName','btnDescription'],(err, values) => {
				if (!err) {
					console.log(values.btnDescription);
					 json={buttonCode:values.btnCode,buttonName:values.btnName,creatorId:parseInt(localStorage.getItem('userId')),menuId:this.state.modalData.id,description:values.btnDescription===undefined?'':values.btnDescription}
			
				} else {
					console.log(err);
				}
			});
		}else{
			this.props.form.validateFields(['buttonCode','buttonName'],(err, values) => {
				if (!err) {
						form.validateFields((error, row) => {
							json={buttonCode:row.buttonCode,buttonName:row.buttonName,updaterId:parseInt(localStorage.getItem('userId')),menuId:this.state.modalData.id,description:row.description,id:key	}
						  });
				} else {
					console.log(err);
				}
			});
		}
		APIService.addOrUpdateBtn(json).then(data=>{
			if(data.data.code===200){
				utils.openNotification('success', '操作成功')
				that.setState({ editingKey: '' });
				that.getBtnByMenuId(that.state.modalData.id);
			}else{
				utils.openNotification('warning', data.data.msg)
			}
		
		 })
		
	}

   //弹出删除框
   showDeleteConfirm = (data) => {
	const that = this;
	confirm({
		title: '确认删除' + '[' + data.name + ']？',
		okText: '确认',
		okType: 'danger',
		cancelText: '取消',
		onOk() {
			if(data.children.length===0){
				APIService.deleteMenu(data.id).then(data => {
					utils.openNotification('success', '删除成功');
					that.fetch(that.state.key);
				}).catch(function (error) {
					utils.openNotification('error', error.message);
				});	
			}else{
				utils.openNotification('warning', '权限有子权限');
			}
				
			

		},
		onCancel() {
			console.log('Cancel');
		},
	});
}

	onExpand=(record, index, indent, expanded)=>{
		
	}
	//选择图标时间
	 click = (e)=> {
		
		 this.setState({
			btnIcon:e
		})
	};
    //0新增  1修改
	create = (data,type) => {
		var first='none';
		var second='none';
		const that=this;
		console.log(this.state.key)
		if(type===1){
			this.props.form.setFieldsValue({
				menuName: data.name,
				address:data.address,
				sort:data.sort
			})
			APIService.getMenuById(data.id).then(res => {
				for(var value of res.data.data){
					if(value.parentId===null){
						that.setState({
							topId:value.id
						})

					}
				}
			}).catch(function (error) {
				utils.openNotification('error', error.message);
			});	
			//判断是第几级菜单
		
		if(data.parentId!==null&&data.children.length!==0){
          first='block';
		}else if(data.parentId!==null&&data.children.length===0){
          second='block';
		}
		}
		
		this.setState({
			visible: true,
			modalData:data,
			btnIcon:type===1?data.icon:'',
			firstLevel:first,
			secondLevel:second,
			handleType:type,
		  });
		
	  };
	 showbtnDrawer=(data)=>{
		 this.getBtnByMenuId(data.id)
		this.setState({
			btnDrawer:true,
			modalData:data,
		  });
	 }
	 //删除按钮
	 deleteBtnById=(id)=>{
         const that=this;
		APIService.deleteBtnById(id).then(data => {
			if(data.data.code===200){
				utils.openNotification('success', '删除成功');
				that.getBtnByMenuId(this.state.modalData.id);
			}else{
				utils.openNotification('warning', data.msg);
			}
			
		}).catch(function (error) {
			utils.openNotification('error', error.message);
		});	
		

	 }

	 getTreeLevel=(id)=>{
		 APIService.getMenuById(id).then(res => {
					
						if(res.data.data.length!==0){
							
							if(res.data.data[0].parentId===null){
								this.setState({
									second:true
								})
							}else{
							}
						}
					})
	 }
	
	  handleCancel = e => {
		this.props.form.resetFields();
		this.setState({
		  visible: false,
		  btnDrawer:false,
		});
	  };

	  isEditing = record => record.id === this.state.editingKey;

	  edit=(key)=> {
		this.setState({ editingKey: key });
	  }

	  cancel = () => {
		this.setState({ editingKey: '' });
	  };
	render() {
		const { loading, dataSource } = this.state;
		const columns = [
			{
				dataIndex:'',
				width:'80px'
			},
			{
				title: '序号',
				width: '10%',
				render:(text,record,index)=> `${index+1}`,
			  },
		
			{
			  title: '菜单名称',
			  dataIndex: 'name',
			},
			{
			  title: '访问地址',
			  dataIndex: 'address',
			},
			{
			  title: '排序',
			  dataIndex: 'sort',
			},
			{
				title: '操作',
				width:'12%',
				render: (text, record) => {
					// record.hierarchy===1||record.hierarchy===2||record.hierarchy===3
						if (record.children.length>0) {
							return	<span>
							  <a onClick={()=>this.create(record,0)}>添加</a>
							  <Divider type="vertical" />
		
							  <a  onClick={()=>this.create(record,1)}>修改</a>
							  <Divider type="vertical" />
							  <a  onClick={()=>this.showDeleteConfirm(record)}>
								删除
							  </a>
							</span>
						}
						else if(record.children.length===0){
							
							return	<span>
							<a onClick={()=>this.create(record,0)}>添加</a>
							<Divider type="vertical" />
	  
							<a  onClick={()=>this.create(record,1)}>修改</a>
							<Divider type="vertical" />
		
							<a onClick={()=>this.showbtnDrawer(record)}>编辑按钮</a>
							<Divider type="vertical" />
							<a  onClick={()=>this.showDeleteConfirm(record)}>
							  删除
							</a>
						  </span>
						}
						

					
					
				
			}
		}
		  ];

		  const btnColumn = [
			{
			  title: '名称编码',
			  dataIndex: 'buttonCode',
			  editable: true,
			},
			{
			  title: '中文名称',
			  dataIndex: 'buttonName',
			  editable: true,
			},
			{
			  title: '描述',
			  dataIndex: 'description',
			  editable: true,
			},
			{
				title: '操作',
				render: (text, record) => {
					const { editingKey } = this.state;
					const editable = this.isEditing(record);
					return editable ? (
					  <span>
						<EditableContext.Consumer>
						  {form => (
							<a
							  onClick={() => this.submitBtn(form,record.id)}
							  style={{ marginRight: 8 }}
							>
							  保存
							</a>
						  )}
						</EditableContext.Consumer>
						<Popconfirm title="Sure to cancel?" onConfirm={() => this.cancel(record.key)}>
						  <a>取消</a>
						</Popconfirm>
					  </span>
					) : (
						<span  disabled={editingKey !== ''}>
					  <a onClick={() => this.edit(record.id)}>
						修改
					  </a>
					  <Divider type="vertical" />
					  <a onClick={() => this.deleteBtnById(record.id)}>
						删除
					  </a>
					  </span>
					)

				
                }
		}
		  ];
	
		const data =this.state.menuList;
		 const { getFieldDecorator } = this.props.form;
		 const formItemLayout = {
            labelCol: {
                xs: {
                    span: 30
                },
                sm: {
                    span: 10
                },
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 14
                },
            },
        };

		const formItemLayout_addMenu = {
			labelCol: {
				sm: { span: 8 }
			},
			wrapperCol: {
				sm: { span: 9 }
			}
		};
			let id = 0;
			let iconData = [
				'home',
				'calendar',
				'tag',
				'link',
				'fork',
				'form',
				'edit',
				'file',
				'global',
				'barcode',
				'crown',
				'copy',
				'select',
			];
			const components = {
				body: {
				  cell: EditableCell,
				},
			  };
			  const column = btnColumn.map(col => {
				if (!col.editable) {
				  return col;
				}
				return {
				  ...col,
				  onCell: record => ({
					record,
					inputType: col.dataIndex === 'age' ? 'number' : 'text',
					dataIndex: col.dataIndex,
					title: col.title,
					editing: this.isEditing(record),
				  }),
				};
			  });
			  //生成按钮
			 var ButtonList = (props) => {
				const buttonData = props.data;
				console.log(buttonData)
				// return <Button  type="primary" onClick={()=>this.create([],0)}>
				// 			新增
				// 		</Button>
				if(buttonData===null){
					return ''
				}
				else if(buttonData.length>0){
					return buttonData.map((item, idx) => (
						<Button key={item.id} type="primary" onClick={()=>this[`${item.buttonCode}`]([],0)}>
							{item.buttonName}
						</Button>
					))
				}else if(buttonData.length===null){
					return ''
				}
				return ''
				
			}
		return (
			<div className="shadow-radius">
				<Tabs tabBarExtraContent={<div className="mydiv"><ButtonList data={JSON.parse(localStorage.getItem('buttonList'))}/></div>} defaultActiveKey="1" onChange={this.handleChangeTab}>
					<TabPane tab="管理端" key="1">
					<Table columns={columns} rowKey={(record)=>record.id} dataSource={data} pagination={false} loading={this.state.loading}   onExpand={(expanded,record)=>this.onExpand(expanded,record )}/>
					</TabPane>
					<TabPane tab="移动端" key="2">
					<Table columns={columns} rowKey={(record)=>record.id} dataSource={data} pagination={false} loading={this.state.loading}   onExpand={(expanded,record)=>this.onExpand(expanded,record )}/>

					</TabPane>
				</Tabs>
				
						<Modal
						width='600px'
				title="新增子菜单"
				visible={this.state.visible}
				centered
				onOk={this.submitMenu}
				onCancel={this.handleCancel}
				okText="保存"
				cancelText="取消"
				>
					<Form {...formItemLayout_addMenu}>
					<Form.Item label="菜单名称">
						{getFieldDecorator('menuName', {
							rules: [{ required: true, message: '请填写菜单名称！' }]
						})(<Input />)}
					</Form.Item>
					<Form.Item label="访问地址">
						{getFieldDecorator('address', {initialValue:'/',
							rules: [{ required: true, message: '请填写访问地址！' }]
						})(<Input />)}
					</Form.Item>
					<Form.Item label="父节点" style={{display:this.state.firstLevel}}>
						{getFieldDecorator('firstNode',{initialValue:this.state.modalData.parentId+''})(<Select>
							{this.state.menuList.map(data => <Option key={data.id}>{data.name}</Option>)}
						</Select>)}
					</Form.Item>
					
				   <Form.Item label="父节点" style={{display:this.state.secondLevel}}>
						{getFieldDecorator('secondNode',{initialValue: [this.state.topId,this.state.modalData.parentId],})(<Cascader options={this.state.options} />)}
					</Form.Item>
					<Form.Item label="图标">
						{getFieldDecorator('icon', {
						})(<Popover  placement='bottomLeft' content={<ul className="list" style={{width:'20rem',height:'10rem',overflow:'auto'}}>
						{iconData.map(item => (
							<li key={id++} style={{width:'calc(100%/5)'}} onClick={this.click.bind(this, item)}>
								<Icon type={item} />
							</li>
						))}
			       </ul>}>
						<Button id="btnIcon" style={{width:'50%'}} icon={this.state.btnIcon}><span style={{display:this.state.btnIcon===''?'block':'none'}}>图标</span></Button>
					  </Popover >)}
					</Form.Item>
					
					<Form.Item label="排序">
						{getFieldDecorator('sort',{initialValue:'1'})(<InputNumber min={1}  />)}
					</Form.Item>
				</Form>

				</Modal>

			

				   {/* 按钮drawer */}
				   <Drawer title="按钮 新增/列表" placement="right" closable={true} onClose={this.handleCancel} visible={this.state.btnDrawer}
                    width='600px' >

                    <Form {...formItemLayout}>
                            <Row gutter={16} >   <Col span={12}> <Form.Item label={< span > 名称编码 </span>}> {getFieldDecorator('btnCode', { rules: [{ required: true, message: '请输入名称编码', whitespace: true }], })
                            (< Input placeholder="请输入名称编码" /> )}
                        </Form.Item >
                        </Col>
				
                        <Col span={12} ><Form.Item label={<span> 中文名称 </span >}> {
                            getFieldDecorator('btnName', { rules: [{ required: true, message: '请输入中文名称', whitespace: true }], })
								(< Input placeholder="请输入中文名称" />)}
								</Form.Item>
                        </Col>
                        </Row >
                            <Row gutter={16}> 
                        <Col span={12}><Form.Item label={< span > 描述 </span>}>
                            {getFieldDecorator('btnDescription',{ rules: [{ whitespace: true }], })
                                (< Input placeholder="请输入描述" />)
                            } </Form.Item>
							</Col >
                                
							<Col span={24} className='btn-style'>
									<Button icon="plus" onClick={()=>this.submitBtn()} type="primary" > 新增 </Button>
							</Col >
                      </Row>

                    </Form >
					<EditableContext.Provider value={this.props.form}>
							<Table  components={components} columns={column} rowKey={(record)=>record.id}   dataSource={this.state.btnData} pagination={false}  />
					</EditableContext.Provider>   

					<div
						style={{
						position: 'absolute',
						right: 0,
						bottom: 0,
						width: '100%',
						borderTop: '1px solid #e9e9e9',
						padding: '10px 16px',
						background: '#fff',
						textAlign: 'right',
						}}
					>
						<Button onClick={this.handleCancel} style={{ marginRight: 8 }}>
						关闭
						</Button>
					</div>
                </Drawer >
			</div>
		);
	}
}
export default Form.create()(Settings);